package com.ljq.MT_Basics;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Description: 解决线程安全的3种方案： 同步代码块、同步方法、锁
 * Author:ljq
 * Date:2025-02-19
 * Time:22:47
 */
public class Ticket implements Runnable {
    private int ticketCount = 100;
    private Object obj = new Object();  // 需要是同一把锁
    Lock l = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            if (ticketCount <= 0) {
                break;
            }
//          同步代码块
/*       synchronized (obj){
           if(ticketCount>0){
               try {
                   Thread.sleep(100);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               System.out.println(Thread.currentThread().getName() +"出售票号"+ticketCount);
               ticketCount--;
           }
           if (ticketCount == 0){
               break;
           }
       }*/

            /*
             同步方法
             foo();*/
            l.lock();
            if (ticketCount > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "出售票号" + ticketCount);
                ticketCount--;
            }
            l.unlock();

        }
    }

    private synchronized void foo() {
        if (ticketCount > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "出售票号" + ticketCount);
            ticketCount--;
        }

    }
}
